package com.shop.shoporder.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.shop.shoporder.common.HttpRequest;
import com.shop.shoporder.common.MessageConstants;
import com.shop.shoporder.common.InterfaceVer;
import com.shop.shoporder.common.Response;
import com.shop.shoporder.entity.order.Config;
import com.shop.shoporder.entity.order.Log;
import com.shop.shoporder.entity.order.logtype;
import com.shop.shoporder.service.ConfigService;
import com.shop.shoporder.service.LogisticsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import net.sf.json.JSONArray;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("logisticsService")
public class LogisticsServiceImpl implements LogisticsService {
    private static final String SYNQUERY_URL = "http://poll.kuaidi100.com/poll/query.do";
    private static MessageDigest mdigest = null;
    private static char digits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
    @Autowired
    ConfigService configService;
    @Override
    public String expressPost(Map<String, String> params) {
            StringBuffer response = new StringBuffer("");
            BufferedReader reader = null;
            try {
                StringBuilder builder = new StringBuilder();
                for (Map.Entry<String, String> param : params.entrySet()) {
                    if (builder.length() > 0) {
                        builder.append('&');
                    }
                    builder.append(URLEncoder.encode(param.getKey(), "UTF-8"));
                    builder.append('=');
                    builder.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
                }
                byte[] bytes = builder.toString().getBytes("UTF-8");

                URL url = new URL(SYNQUERY_URL);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setConnectTimeout(3000);
                conn.setReadTimeout(3000);
                conn.setRequestMethod("POST");
                conn.setRequestProperty("accept", "*/*");
                conn.setRequestProperty("connection", "Keep-Alive");
                conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                conn.setRequestProperty("Content-Length", String.valueOf(bytes.length));
                conn.setDoOutput(true);
                conn.getOutputStream().write(bytes);

                reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));

                String line = "";
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (null != reader) {
                        reader.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            return response.toString();
        }

    @Override
    public MessageDigest getMdInst() {
        if (null == mdigest) {
            try {
                mdigest = MessageDigest.getInstance("MD5");
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
        }
        return mdigest;
    }

    @Override
    public String encode(String s) {
        if(null == s) {
            return "";
        }
        try {
            byte[] bytes = s.getBytes();
            getMdInst().update(bytes);
            byte[] md = getMdInst().digest();
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = digits[byte0 >>> 4 & 0xf];
                str[k++] = digits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public String synQueryData(String com, String num, String phone, String from, String to, int resultv2) {
        Config config=configService.selectByPrimaryKey(1);
        com=getLogType(num);
        StringBuilder param = new StringBuilder("{");
        param.append("\"com\":\"").append(com).append("\"");
        param.append(",\"num\":\"").append(num).append("\"");
        param.append(",\"phone\":\"").append(phone).append("\"");
        param.append(",\"from\":\"").append(from).append("\"");
        param.append(",\"to\":\"").append(to).append("\"");
        if(1 == resultv2) {
            param.append(",\"resultv2\":1");
        } else {
            param.append(",\"resultv2\":0");
        }
        param.append("}");
        Map<String, String> params = new HashMap<String, String>();
        params.put("customer", config.getExpressCustomer());
        String sign = encode(param + config.getExpressKey() + config.getExpressCustomer());
        params.put("sign", sign);
        params.put("param", param.toString());
        return expressPost(params);
    }

    @Override
    public Response getExpressNoData(Map<String, String> map, HttpServletRequest request) throws Exception {
        String logisticsNo="";
        JSONObject jsonObject=new JSONObject();
        if (map != null) {
            logisticsNo = InterfaceVer.VerStr(map.get("logisticsNo"));
            String expressData=synQueryData("",logisticsNo,"","","",0);
            jsonObject=JSONObject.parseObject(expressData);
            return new Response(MessageConstants.MSG_SUCCESS, jsonObject, 1, "获取成功!", request);
        }
        return new Response(MessageConstants.MSG_SUCCESS, jsonObject, 1, "获取失败!", request);
    }

    @Override
    public String getLogType(String logno) {
        String expressKey = "fUVnugio6599";
        try {
            if (logno!=null) {
//                logno="822492462394";
                String url = "http://www.kuaidi100.com/autonumber/auto";
                String userNoId = "num=" + logno;
                userNoId +="&key"+expressKey;
                String s="";
                String result = HttpRequest.sendGet(url, userNoId);

                List<logtype> datas = null;
                JSONArray jsonArr = JSONArray.fromObject(result);
                datas = (List<logtype>) JSONArray.toCollection(jsonArr, logtype.class);
                //JSONObject str = JSONObject.parseObject(result);
                if(datas!=null&&datas.size()>0){
                    logtype logtype1=datas.get(0);
                    String type=logtype1.getComCode();
                    //System.out.println("a1");
                    return type;
                }else {
                    //System.out.println("a2");
                    return "huitongkuaidi";
                }
            }else {
                //System.out.println("a3");
                return "huitongkuaidi";
            }
        }catch (Exception e){
            //System.out.println("a4");
            return "huitongkuaidi";
        }
    }
}
